package cn.intcast.order.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.List;

import cn.intcast.order.R;
import cn.intcast.order.bean.FoodBean;

public class CarAdapter extends BaseAdapter {
    private Context mContext;
    private List<FoodBean> fbl;
    private OnSelectListener onSelectListener;

    public CarAdapter(Context mContext, OnSelectListener onSelectListener) {
        this.mContext = mContext;
        this.onSelectListener = onSelectListener;
    }

    public void setData(List<FoodBean> fbl) {
        this.fbl = fbl;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return fbl == null ? 0 : fbl.size();
    }

    @Override
    public FoodBean getItem(int i) {
        return fbl == null ? null : fbl.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        final ViewHolder vh;
        if (view == null) {
            vh = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.car_item, null);
            vh.tv_food_name = view.findViewById(R.id.tv_food_name);
            vh.tv_food_count = view.findViewById(R.id.tv_food_count);
            vh.tv_food_price = view.findViewById(R.id.tv_food_price);
            vh.iv_add = view.findViewById(R.id.iv_add);
            vh.iv_minus = view.findViewById(R.id.iv_minus);
            view.setTag(vh);
        } else {
            vh = (ViewHolder) view.getTag();
        }
        final FoodBean bean = getItem(i);
        if (bean != null) {
            vh.tv_food_name.setText(bean.getFoodName());
            vh.tv_food_count.setText(bean.getCount() + "");
            BigDecimal count = BigDecimal.valueOf(bean.getCount());
            vh.tv_food_price.setText("￥" + bean.getPrice().multiply(count));
        }
        vh.iv_add.setOnClickListener(view1 -> {
            onSelectListener.onSelectAdd(i, vh.tv_food_count, vh.
                    tv_food_price);
        });

        vh.iv_minus.setOnClickListener(view1 -> {
            onSelectListener.onSelectMis(i, vh.tv_food_count, vh.
                    tv_food_price);
        });
        return view;
    }

    class ViewHolder {
        public TextView tv_food_name, tv_food_count, tv_food_price;
        public ImageView iv_add, iv_minus;
    }

    public interface OnSelectListener {
        void onSelectAdd(int position, TextView tv_food_price, TextView tv_food_count);

        void onSelectMis(int position, TextView tv_food_price, TextView tv_food_count);

    }
}
